package com.seestech.sell.web.agent;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.seestech.sell.domain.model.*;
import com.seestech.sell.common.annotation.Duplicate;
import com.seestech.sell.common.annotation.RecordLog;
import com.seestech.sell.common.utils.Constants;
import com.seestech.sell.common.utils.JsonUtils;
import com.seestech.sell.common.utils.ResponseUtils;
import com.seestech.sell.domain.model.enums.StatusEnums;
import com.seestech.sell.service.*;
import com.seestech.sell.web.SuperController;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Created by idiot on 2017/6/19.
 */
@Controller
@RequestMapping(value = "shelf")
public class ShelfController extends SuperController {
    private static Logger logger = LoggerFactory.getLogger(ShelfController.class);

    @Resource
    private IShelfService shelfService;
    @Resource
    private IShelfDetailService shelfDetailService;
    @Resource
    private IAgentService agentService;

    //加载page页面
    @RequiresPermissions(value = "shelf:page")
    @RequestMapping(value = "page", method = RequestMethod.GET)
    public String toPage(Model model){
        logger.info("加载货架页面信息=====》》》");
        return "shelf/page";
    }

    //加载data页面
    @RequestMapping(value = "data", method = RequestMethod.POST)
    public String data(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, Shelf info, Model model){
        User user = getUser();
        if(user == null){
            logger.error("获取品牌信息======>>>>>>>>用户信息失效，请重新登录");
            return "login";
        }
        //获取这个用户所在企业相关的用户信息
        Set<Long> userIds = getUserIds(user);
        userIds.add(user.getUserId());
        info.setUserIds(userIds);
        info.setCreateUser(null);
        info.setStatus(StatusEnums.VALID.getValue());
        Page<Shelf> lists = shelfService.getAllShelfs(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", lists);
        return "shelf/data";
    }

    //加载编辑页面
    @RequestMapping(value = "toUpdate", method = RequestMethod.GET)
    public String toAdd(Model model){
        return "shelf/update";
    }

    //编辑信息
    @Duplicate
    @RecordLog(value = "修改货架信息")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public void update(Shelf info){
        User user = getUser();
        if(user == null || user.getUserId() == null) {
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "用户信息有误，新增终端分组信息失败");
            return;
        }
        //根据名称获取货架信息
        List<Shelf> shelfs = shelfService.getShelfsByName(info.getName());
        //menuId为空/0时表示   新增操作
        if(info.getShelfId() == null){
            if(shelfs != null && shelfs.size() > 0){
                ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "新增货架信息失败，该名称已经存在");
                return;
            }
            info.setCreateUser(getUser().getUserId());
            shelfService.insert(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "新增货架信息成功");
        }else {     //修改操作
            if(shelfs != null && shelfs.size() == 1){
                // 获取第一个  判断主键是否相同
                Shelf shelf = shelfs.get(0);
                if(shelf.getShelfId().equals(info.getShelfId())){
                    ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "修改货架信息失败，该名称已经存在");
                    return;
                }
            }else {
                ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "修改货架信息失败，该名称已经存在");
                return;
            }
            Long[] shelfIds = new Long[]{info.getShelfId()};
            List<Agent> list = agentService.getAgentsByShelfIds(shelfIds);
            if(list != null && list.size() > 0){
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "该货架已经绑定终端信息，不能修改");
                return;
            }
            info.setUpdateUser(getUser().getUserId());
            shelfService.update(info);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "修改货架信息成功");
        }
    }


    //加载编辑页面
    @RequestMapping(value = "{shelfId}/toUpdate", method = RequestMethod.GET)
    public String toUpdate(@PathVariable("shelfId") Long shelfId, Model model){
        //查询货架信息
        Shelf shelf = shelfService.getShelfByShelfId(shelfId);
        model.addAttribute("shelf",shelf);
        return "shelf/update";
    }

    //删除品牌信息
    @RecordLog(value = "删除货架信息")
    @RequestMapping(value = "{shelfId}/delete", method = RequestMethod.POST)
    public void delete(@PathVariable("shelfId") Long shelfId){
        Long[] shelfIds = new Long[]{shelfId};
        List<Agent> list = agentService.getAgentsByShelfIds(shelfIds);
        if(list != null && list.size() > 0){
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "该货架已经绑定终端信息，不能删除");
        }else {
            shelfService.delete(shelfId);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "删除货架信息成功");
        }
    }

    //批量删除
    @RequestMapping(value = "deleteBatch", method = RequestMethod.POST)
    public void deleteBatch(@RequestParam("ids[]") Long[] shelfIds){
        List<Agent> list = agentService.getAgentsByShelfIds(shelfIds);
        if(list != null && list.size() > 0){
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "该货架已经绑定终端信息，不能删除");
        }else {
            shelfService.deleteBatch(shelfIds);
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "批量删除货架信息成功");
        }
    }

    /**********************************************详情页面****/
    //加载编辑页面
    @RequestMapping(value = "{shelfId}/toDetailPage", method = RequestMethod.GET)
    public String toDetail(@PathVariable("shelfId") Long shelfId, Model model){
        model.addAttribute("shelfId", shelfId);
        return "shelf/detailPage";
    }

    //加载data页面
    @Deprecated
    @RequestMapping(value = "detailData", method = RequestMethod.POST)
    public String detailData(Integer pageNo, @RequestParam(defaultValue="10")Integer pageSize, ShelfDetail info, Model model){
        Page<Shelf> lists = shelfDetailService.getAllShelfDetails(new RowBounds((pageNo-1)*pageSize, pageSize), info);
        model.addAttribute("lists", lists);
        return "shelf/detailData";
    }

    //加载编辑页面
    @RequestMapping(value = "toDetailUpdate", method = RequestMethod.GET)
    public String toAddDetail(Model model, Long shelfId){
        if(shelfId != null){
            Shelf shelf = shelfService.getShelfByShelfId(shelfId);
            model.addAttribute("shelf", shelf);
        }
        return "shelf/detailUpdate";
    }

    //编辑信息
    @Duplicate
    @RecordLog(value = "修改货架详情信息")
    @RequestMapping(value = "detailUpdate", method = RequestMethod.POST)
    public void update(ShelfDetail info){
        //检测该货架是否已经绑定终端
        Long[] shelfIds = new Long[]{info.getShelfId()};
        List<Agent> list = agentService.getAgentsByShelfIds(shelfIds);
        if(list != null && list.size() > 0){
            ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "该货架已经绑定终端信息，不能编辑");
        }else {
            //menuId为空/0时表示   新增操作
            if(info.getDetailId() == null){
                info.setCreateUser(getUser().getUserId());
                shelfDetailService.insert(info);

                if(shelfService.modifyShelf(info.getShelfId()))
                    ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "新增货架详情信息成功");
                else
                    ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "新增货架详情信息失败");
            }else {     //修改操作
                info.setUpdateUser(getUser().getUserId());
                shelfDetailService.update(info);

                if(shelfService.modifyShelf(info.getShelfId()))
                    ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "修改货架详情信息成功");
                else
                    ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "修改货架详情信息失败");
            }
        }
    }


    //加载编辑页面
    @RequestMapping(value = "{detailId}/toDetailUpdate", method = RequestMethod.GET)
    public String toDetailUpdate(@PathVariable("detailId") Long detailId, Long shelfId, Model model){
        if(shelfId != null){
            Shelf shelf = shelfService.getShelfByShelfId(shelfId);
            model.addAttribute("shelf", shelf);
        }

        //查询货架信息
        ShelfDetail shelfDetail = shelfDetailService.getShelfDetailByDetailId(detailId);
        model.addAttribute("shelfDetail",shelfDetail);
        return "shelf/detailUpdate";
    }

    //删除信息
    @RecordLog(value = "删除货架详情信息")
    @RequestMapping(value = "{detailId}/detailDelete", method = RequestMethod.POST)
    public void detailDelete(@PathVariable("detailId") Long detailId){
        ShelfDetail info = shelfDetailService.getShelfDetailByDetailId(detailId);
        if(info == null)
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "删除货架详情信息失败");
        else {
            Long[] shelfIds = new Long[]{info.getShelfId()};
            List<Agent> list = agentService.getAgentsByShelfIds(shelfIds);
            if(list != null && list.size() > 0) {
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "该货架已经绑定终端信息，不能删除");
                return;
            }
            shelfDetailService.delete(detailId);

            if(shelfService.modifyShelf(info.getShelfId()))
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "删除货架详情信息成功");
            else
                ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "删除货架详情信息失败");
        }
    }

    //批量删除
    @RequestMapping(value = "detailDeleteBatch", method = RequestMethod.POST)
    public void detailDeleteBatch(@RequestParam("ids[]") Long[] detailIds){
        //取出首个货架详情信息   判断非空   拿到shelfId
        ShelfDetail info = shelfDetailService.getShelfDetailByDetailId(detailIds[0]);
        if(info == null)
            ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "批量删除货架详情信息失败");
        else {
            shelfDetailService.deleteBatch(detailIds);

            if(shelfService.modifyShelf(info.getShelfId()))
                ResponseUtils.writeSuccessResponse(request_local.get(), response_local.get(), "批量删除货架详情信息成功");
            else
                ResponseUtils.writeErrorResponse(request_local.get(), response_local.get(), "批量删除货架详情信息失败");
        }
    }


    /*********************************/

    //货架详情数据接口
    @ResponseBody
    @RequestMapping(value = "detailData.json", method = RequestMethod.POST)
    public Object detailData(ShelfDetail info){
        logger.info("获取货架详情接口信息......");
        ResultBean<Object> resultBean;
        Page<Shelf> lists = shelfDetailService.getShelfDetails(info);
        //json数据  长整型转换为字符串
        JSONArray object = JsonUtils.parseArray(lists);
        resultBean = ResponseUtils.initResultBean(object, Constants.ResponseCode.success, "成功", true);
        resultBean.setTotalCount(lists == null ? 0 :(int) lists.getTotal());
        return resultBean;
    }

    //获取货架信息接口
    @ResponseBody
    @RequestMapping(value = "getShelfs.json")
    public Object getShelfs(){
        logger.info("获取货架信息接口......");
        ResultBean<Object> resultBean;
        Shelf info = new Shelf();
        info.setStatus(StatusEnums.VALID.getValue());
        List<Shelf> lists = shelfService.getShelfs(info);
        //json数据  长整型转换为字符串
        JSONArray object = JsonUtils.parseArray(lists);
        resultBean = ResponseUtils.initResultBean(object, Constants.ResponseCode.success, "成功", true);
        resultBean.setTotalCount(lists == null ? 0 : lists.size());
        return resultBean;
    }

}
